package org.testis.webautomationmodule.ui;

import org.testis.data.TestStepException;
import org.testis.data.TestStepResultType;
import java.util.ArrayList;


import org.testis.webautomationmodule.data.WebAutomationModuleDataNode;
import org.testis.webautomationmodule.services.WebAutomationProviderImpl;


/**
 * A class for building web automation test step object
 * for the given data
 * @author nurhat
 */
public class WebAutomationTestStepBuilder
{

    /**
     * Holds ui object list
     */
    private ArrayList<WebAutomationDecorator> m_decoList;
    /**
     * Holds current web autmation implementation
     */
    private WebAutomationProviderImpl m_automateImpl;


    /**
     * Creates a web automation test step builder
     * @param data 
     * @param m_automateImpl
     */
    public WebAutomationTestStepBuilder(WebAutomationProviderImpl automateImpl)
    {

        m_decoList = new ArrayList<WebAutomationDecorator>();
        this.m_automateImpl = automateImpl;
    }


    /**
     * Creates ui object for the given data and connects ui objects to each other
     * @return parent ui object decorator
     * @throws org.testis.dut.exceptions.WebAutomationException
     */
    public WebAutomationDecorator createTestStep(
        ArrayList<WebAutomationModuleDataNode> list,String msgId)
    {
        if (list == null) {
            return null;
        }
        UIObjectCreator fac = new UIObjectCreator();
        WebAutomationDecorator decorator;
        for (int i = 0; i < list.size(); i++) {
            decorator = fac.createUIObject(list.get(i).getObjectType(),
                                           list.get(i).getParameters(),msgId);
            if (decorator != null) {
                decorator.setWebAutomationImpl(m_automateImpl);
                decorator.setAbstractId(list.get(i).getAbstractId());
                m_decoList.add(decorator);
            }
            else {
                throw new TestStepException(
                    TestStepResultType.MISTAKE,
                    " at WebAutomationTestStepDriver " +
                    "Could not create object ( " +
                    list.get(i) + ")");
            }
        }
        //connect decorators to each other
        if (m_decoList.size() > 1) {
            for (int i = 0; i < m_decoList.size() - 1; i++) {
                m_decoList.get(i).setNextUIObjectDecorator(m_decoList.get(i + 1));
            }
        }
        //return reference to first decorator object
        if (m_decoList != null) {
            if (m_decoList.size() > 0) {
                return m_decoList.get(0);
            }
        }
        return null;
    }
}

